package cn.htu.mpp.web.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

@Configuration
@PropertySource(value = "classpath:/jdbc.properties")
public class DataAccessConfig{
	
	@Value("${connection.username}")
	private String username;
	
	@Value("${connection.password}")
	private String password;
	
	@Value("${connection.url}")
	private String jdbcUrl;
	
	@Value("${driver.classname}")
	private String driverClassName;
	
	@Bean
	public DataSource dataSource() {
		
		HikariConfig hikariConfig = new HikariConfig();
		
		hikariConfig.setUsername(username);
		
		hikariConfig.setPassword(password);
		
		hikariConfig.setJdbcUrl(jdbcUrl);
		
		hikariConfig.setDriverClassName(driverClassName);
		
		HikariDataSource hikariDataSource = new HikariDataSource(hikariConfig);
		
		return hikariDataSource;
	}
	
	@Bean
	public LocalSessionFactoryBean sessionFactory(@Autowired DataSource dataSource) {
		
		LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
		
		localSessionFactoryBean.setDataSource(dataSource);
		
		localSessionFactoryBean.setPackagesToScan("cn.htu.mpp.entity");
				
		return localSessionFactoryBean;
	}
	
	@Bean
	public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
		
		return new PropertySourcesPlaceholderConfigurer();
	}
	
}
